package com.chenjiajin.config;

import feign.Feign;
import feign.Logger;
import feign.RequestInterceptor;
import feign.Retryer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * @author ChenJiaJin
 */
@Configuration
@ConditionalOnClass(Feign.class)   // 这里就是判断你是否引入了 Feign类相关依赖，引入依赖后该条件成立，当前类的配置才会生效！
// 就是说只有在classpath下能找到Feign类才会构建这个bean
public class OpenFeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            // ServletRequestAttributes可以获取session -->  attributes.getRequest().getSession()
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (null != attributes) {
                HttpServletRequest request = attributes.getRequest();
                requestTemplate.header("Authorization", request.getHeader("Authorization"));
                //System.err.println("FeignRequestInterceptor = " + requestTemplate);
                //System.err.println("sessionId = " + attributes.getSessionId());
            }
        };
    }

    /**
     * 日志级别
     */
    @Bean
    public Logger.Level level() {
        return Logger.Level.FULL;
        /*
          日志级别:
          NONE：默认的，不显示任何日志；
          BASIC：仅记录请求方法、URL、响应状态码及执行时间；
          HEADERS：除了 BASIC 中定义的信息之外，还有请求和响应的头信息；
          FULL：除了 HEADERS 中定义的信息之外，还有请求和响应的正文及元数据
         */
    }

    /**
     * 不重试
     */
    @Bean
    Retryer retryer() {
        return Retryer.NEVER_RETRY;
    }

}
